package com.semlab.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SimplePanel;
import com.semlab.client.app.gin.Injector;
import com.semlab.client.bundle.Resources;
import com.semlab.client.events.FBLoginEvent;

public class FBButton extends Composite implements HasClickHandlers {

    private SimplePanel container;
    private static final String API_ID = "366007943430825";
    Image image = new Image(Resources.INSTANCE.facebook());

    public FBButton() {
        container = new SimplePanel();
        initWidget(container);
        initAPI(API_ID);
        image.addStyleName(Resources.INSTANCE.css().hand());
        image.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                login();
            }
        });
        container.setWidget(image);
    }

    private native void initAPI(String key) /*-{
        $wnd.FB.init({
            appId:key,
            channelURL:'//channel.html',
            status:true,
            cookie:true,
            oauth:true,
            xfbml:true
        });
    }-*/;

    private native void login()/*-{
        client = new Object();
        $wnd.FB.login(function (response) {
            if (response.authResponse) {
                client.accessToken = response.authResponse.accessToken;
                $wnd.FB.api('/me', function (response) {
                    client.name = response.name;
                    client.id = response.id;
                    @com.semlab.client.widgets.FBButton::onComplete(Lcom/semlab/client/widgets/SocialClient;)(client);
                });
            } else {
                @com.semlab.client.widgets.FBButton::onComplete(Lcom/semlab/client/widgets/SocialClient;)(null);
            }
        }, {scope:"user_about_me , friends_about_me, friends_birthday , friends_education_history , friends_events , friends_hometown , friends_interests , friends_likes , friends_location , friends_website , offline_access" });

    }-*/;

    private static native void logout()/*-{
        $wnd.FB.logout(function (response) {
        });
    }-*/;


    public static void onComplete(SocialClient client) {
        GWT.log("sc = " + client.getName());
        Injector.INSTANCE.getEventBus().fireEvent(new FBLoginEvent(client));
//		logout();
    }

    @Override
    public HandlerRegistration addClickHandler(ClickHandler handler) {
        return image.addClickHandler(handler);
    }
}
